<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>binarySearch</title>
</head>

<body>
    <div>打开浏览器控制台查看结果</div>
    <script>
        const binarySearch = (arr, item) => {
            let l = 0,
                r = arr.length - 1;
            while (l <= r) {
                const m = Math.floor((l + r) / 2);
                if (arr[m] === item) {
                    return m;
                } else if (arr[m] > item) {
                    r = m - 1;
                } else {
                    l = m + 1;
                }
            }
            return -1;
        };
        console.log(binarySearch([1, 2, 3, 4, 5], 1)); // 0
        console.log(binarySearch([1, 2, 3, 4, 5], 5)); // 4
        console.log(binarySearch([1, 2, 3, 4, 5], 6)); // -1
    </script>
</body>

</html>